# -*- coding: utf-8 -*-
# @Time   : 2024-03-14 14:36
# @Author : 大龙 🚀

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
from utils.tools import urlencode


class HunanCdsrmzf1197Policy(BaseTaxPolicySpider):
    name = 'hunan_cdsrmzf_1197_policy'

    province = "湖南省"
    city = "常德市"
    county = ""
    park = ""
    source = "常德市人民政府"
    home_url = "https://www.changde.gov.cn/zwgk/site/tpl/4995?organId=6616760&catId=6719290&tabs=1"
    url = "https://www.changde.gov.cn/zwgk/site/label/8888"
    params = {
        "_": "0.008309234646722174",
        "labelName": "publicInfoList",
        "siteId": "6796502",
        "pageSize": "10",
        "pageIndex": "1",
        "action": "list",
        "isDate": "false",
        "dateFormat": "yyyy-MM-dd",
        "length": "50",
        "organId": "6616760",
        "type": "4",
        "catId": "6719290",
        "cId": "",
        "keyWords": "",
        "searchType": "",
        "result": "",
        "policyThemeTypes": "",
        "file": "/c1/xxgk/publicInfoList_newest_policy"
    }

    def start_requests(self):
        yield scrapy.Request(self.url + '?' + urlencode(self.params), callback=self.parse_list)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath("//ul/li[not(@id)]//a[contains(@href, 'htm') or @title]/ancestor::li[string-length(string(.))>=10] | //dl/dt[not(@id)]//a[contains(@href, 'htm') or @title]/ancestor::dt[string-length(string(.))>=10] | //tr/td[not(@id)]//a[contains(@href, 'htm') or @title]/ancestor::td[string-length(string(.))>=10]"):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total_page = response.xpath("""//script""").re_first(r"""pageCount:(\d+),""")
            for page_num in range(1, int(total_page) + 1):
                self.params['pageIndex'] = str(page_num)
                yield response.follow(self.url + '?' + urlencode(self.params), callback=self.parse_list,
                                      meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline
    cmdline.execute("scrapy crawl hunan_cdsrmzf_1197_policy".split())
